package com.ruoyi.web.controller.tool.designpattern.behavioralPatterns.strategy;

/**
 * TODO
 *
 * @author Hack2003
 * @date 2024/3/20 15:59
 **/
// 策略接口
interface Strategy {
    int doOperation(int num1, int num2);
}

// 具体策略 A
class ConcreteStrategyAdd implements Strategy {
    @Override
    public int doOperation(int num1, int num2) {
        return num1 + num2;
    }
}

// 具体策略 B
class ConcreteStrategySubtract implements Strategy {
    @Override
    public int doOperation(int num1, int num2) {
        return num1 - num2;
    }
}

// 环境类:维持一个对策略对象的引用，可以在运行时切换不同的策略。
class Context {
    private Strategy strategy;

    public Context(Strategy strategy) {
        this.strategy = strategy;
    }

    public int executeStrategy(int num1, int num2) {
        return strategy.doOperation(num1, num2);
    }
}

/**
 * 策略模式有助于实现算法的封装和解耦，
 * 使得算法可以独立于客户端而变化。
 * 它通常用于需要在运行时选择不同算法的情况下。
 */
public class Test {
    public static void main(String[] args) {
        Context context = new Context(new ConcreteStrategyAdd());
        System.out.println("10 + 5 = " + context.executeStrategy(10, 5));

        context = new Context(new ConcreteStrategySubtract());
        System.out.println("10 - 5 = " + context.executeStrategy(10, 5));
    }
}